package com.nongtai.task;

import com.nongtai.constant.RedisConstant;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 定时任务删除redis中的key
 * @author yza
 * @version 1.0
 * @date 2024/7/8 11:40
 */
@Component
public class RedisDeleteKeyTask {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    private static final int BATCH_SIZE = 100;
    /**
     * 每天凌晨两点删除 24小时商品排行榜
     */
    @Scheduled(cron = "0 0 2 * * ? ")
    public void deleteRankKeyWithOneDayExpiration(){
        // 找到所有 "rank:sales:oneDay" 开头的key
        ScanOptions options = ScanOptions
                .scanOptions()
                .match(RedisConstant.RANK_HOT_ONE_DAY + "*")
                .count(BATCH_SIZE)
                .build();

        try (Cursor<String> cursor = redisTemplate.scan(options)) {
            while (cursor.hasNext()) {
                String key = cursor.next();
                boolean hasMoreElements = true;
                long start = 0;
                while (hasMoreElements) {
                    // 删除从start开始的BATCH_SIZE个元素
                    redisTemplate.opsForZSet().removeRange(key, start, start + BATCH_SIZE - 1);
                    // 检查ZSET是否还存在元素
                    hasMoreElements = redisTemplate.opsForZSet().zCard(key) > 0;
                    start += BATCH_SIZE;
                }
                // 当ZSET不再有元素时，删除整个键
                redisTemplate.delete(key);
            }
        }
    }
}
